package com.vnp.cooking.fragmenthome;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockListFragment;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.viewpagerindicator.CirclePageIndicator;
import com.vnp.cooking.ChinhsuaThongtinActivity;
import com.vnp.cooking.CongthucDaThichActivity;
import com.vnp.cooking.CongthucDadangActivity;
import com.vnp.cooking.ListTenBoSuuTapActivity;
import com.vnp.cooking.LoginActivity;
import com.vnp.cooking.R;
import com.vnp.cooking.UIcontrols.MyCircleImageView;
import com.vnp.cooking.UIcontrols.MyClickAbleImageView;
import com.vnp.cooking.adapter.CanhanListAdapter;
import com.vnp.cooking.bean.ObjChef;
import com.vnp.cooking.bean.ObjCookpad;
import com.vnp.cooking.fragmentKitchen.CoverCanhan1;
import com.vnp.cooking.fragmentKitchen.CoverCanhan2;
import com.vnp.cooking.httpclient.HttpClientHelper;
import com.vnp.cooking.httpclient.MyJsonHttpResponseHandler;
import com.vnp.cooking.utils.HelperListview;
import com.vnp.cooking.utils.PreferenceHelper;
import com.vnp.cooking.utils.Utils;

public class FrgGianbepcuatoi extends SherlockListFragment implements OnClickListener{

	View view;
	ScrollView scr;
	CanhanListAdapter adapter;
	ArrayList<ObjCookpad> objCookpads = new ArrayList<ObjCookpad>();
	MyCircleImageView imgAvatar;
	// dialog settings
	ImageButton showDialog;
	Dialog dialog, dH;
	
	// icon 
	MyClickAbleImageView btnDaDang, btnDaThich, btnThongbao, btnHuyhieu, btnBanbe, btnDiemthuong;
	DisplayImageOptions options = new DisplayImageOptions.Builder()
									.cacheInMemory(false)
									.cacheOnDisc(true)
									.bitmapConfig(Config.RGB_565)
									.build();
	
	// xu li cover
	ViewPager pager;
	MyFragmentPagerAdapter myFragmentPagerAdapter;
	CirclePageIndicator indicator;
	PreferenceHelper preferenceHelper;
	
	TextView txtNameTitle;
	ObjChef objChef = new ObjChef();
	
	// load more activity
	ProgressBar prbLoadActivity;
	ProgressBar progressBarLoadmore;
	Button btnLoadMore;
	View  footerMain;
	int mPage = 0;
	Handler mHandler = new Handler();
	
	Runnable rA = new Runnable() {
		
		@Override
		public void run() {
			getActivityUser(mPage);
		}
	}; 
	
	WebView web;
	String urllogout = "http://anuong.net/api/user/logout";
	String urlRsLogout = "http://anuong.net/api/user/logout?status";
	ProgressDialog progressDialog;
	
	TextView txtDadang, txtYeuthich;
	
	View actionbar;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
			view = (View) inflater.inflate(R.layout.frg_home_gianbepcuatoi,
					container, false);
			preferenceHelper = new PreferenceHelper(getActivity());
			
			actionbar = (View) view.findViewById(R.id.actionbar);
			
			scr = (ScrollView) view.findViewById(R.id.scrollView1);
			imgAvatar = (MyCircleImageView) view.findViewById(R.id.img_avatar);
			showDialog = (ImageButton) view.findViewById(R.id.btn_settings);
			pager = (ViewPager) view.findViewById(R.id.viewpager);
			myFragmentPagerAdapter = new MyFragmentPagerAdapter(getChildFragmentManager());
			indicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
			prbLoadActivity = (ProgressBar) view.findViewById(R.id.prgGetActivity);
			
			txtNameTitle = (TextView) view.findViewById(R.id.txt_my_name);
			// khai bao cac icon
			btnDaDang = (MyClickAbleImageView) view.findViewById(R.id.btn_dadang);
			txtDadang = (TextView) view.findViewById(R.id.txt_dadang);
			
			btnDaThich = (MyClickAbleImageView) view.findViewById(R.id.btn_dathich);
			txtYeuthich = (TextView) view.findViewById(R.id.txt_yeuthich);
			
			btnBanbe = (MyClickAbleImageView) view.findViewById(R.id.btn_banbe);
			btnHuyhieu = (MyClickAbleImageView) view.findViewById(R.id.btn_huyhieu);
			btnThongbao = (MyClickAbleImageView) view.findViewById(R.id.btn_thongbao);
			btnDiemthuong = (MyClickAbleImageView) view.findViewById(R.id.btn_diemthuong);
			
			web = (WebView) view.findViewById(R.id.webView);
			
			getInfoUser();
			getActivityUserHandler();
			init();
			setFont();
			
		return view;
	}
	
	void setFont() {
		txtNameTitle.setTypeface(Utils.getTypefaceRegular(getActivity()));
	}
	
	
	void getActivityUserHandler() {
		mHandler.removeCallbacks(rA);
		mHandler.postDelayed(rA, 300);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		getActivityUser(mPage);
		adapter  = new CanhanListAdapter(getActivity(), objCookpads);
		getListView().setAdapter(adapter);
		setListViewHeightBasedOnChildren(getListView());
		addFooterView();
	}
	
	public void init() {
		txtNameTitle.setText(preferenceHelper.getUserInfoName());
		scr.scrollTo(-150, -150);
		pager.setAdapter(myFragmentPagerAdapter);
		indicator.setViewPager(pager);
		showDialog.setOnClickListener(this);
		
		btnDaDang.setOnClickListener(this);
		btnDaThich.setOnClickListener(this);
		btnBanbe.setOnClickListener(this);
		btnDiemthuong.setOnClickListener(this);
		btnHuyhieu.setOnClickListener(this);
		btnThongbao.setOnClickListener(this);
		
		actionbar.setOnClickListener(this);
	}
	
	
	
	
	@Override
	public void onResume() {
		super.onResume();
		txtNameTitle.setText(preferenceHelper.getUserInfoName());
		scr.scrollTo(-150, -150);
	}

	
	// dialog settings
	public void showDialogSettings() {
		dialog = new Dialog(getActivity(), R.style.DialogSlideAnim);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_settings);

		// set cac phan tu ben trong
		Button btnEditTk = (Button) dialog.findViewById(R.id.btn_chinhsua_tk);
		Button btnDangxuat = (Button) dialog
				.findViewById(R.id.btn_dangxuat);
		Button btnThoat = (Button) dialog.findViewById(R.id.btn_thoat);

		
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
	    lp.copyFrom(dialog.getWindow().getAttributes());
	    lp.width = WindowManager.LayoutParams.MATCH_PARENT;
	    lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
		
		
		dialog.setCanceledOnTouchOutside(true);
		dialog.show();
		dialog.getWindow().setAttributes(lp);
		dialog.getWindow().setGravity(Gravity.BOTTOM);
		dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		
		// xu li onclick cac nut
		btnEditTk.setOnClickListener(this);
		btnDangxuat.setOnClickListener(this);
		btnThoat.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		
		case R.id.actionbar:
			break;
		
		case R.id.btn_chinhsua_tk:
			Intent t = new Intent(getActivity(), ChinhsuaThongtinActivity.class);
			dialog.dismiss();
			getActivity().startActivity(t);
			getActivity().overridePendingTransition(R.anim.open_next, R.anim.close_main);
			break;
		case R.id.btn_dangxuat:
			progressDialog = ProgressDialog.show(getActivity(), "", "Đang thoát...");
			mHandler.postDelayed(new Runnable() {

				@Override
				public void run() {
					if (null != progressDialog && progressDialog.isShowing())
						progressDialog.dismiss();
				}
			}, 90000);
			logout();
			dialog.dismiss();
			break;
		case R.id.btn_thoat:
			dialog.dismiss();
			break;
		case R.id.btn_settings:
			showDialogSettings();
			break;
		case R.id.btn_dadang:
			Intent a = new Intent(getActivity(), CongthucDadangActivity.class);
			a.putExtra("userID", preferenceHelper.getID());
			startActivity(a);
			getActivity().overridePendingTransition(R.anim.open_next, R.anim.close_main);
			break;
		case R.id.btn_dathich:
			Intent c = new Intent(getActivity(), CongthucDaThichActivity.class);
			c.putExtra("userID", preferenceHelper.getID());
			startActivity(c);
			getActivity().overridePendingTransition(R.anim.open_next, R.anim.close_main);
			break;
			
		case R.id.btn_load_more:
			mPage = mPage + 1;
			progressBarLoadmore.setVisibility(View.VISIBLE);
			btnLoadMore.setText("Đang lấy thêm...");
			getActivityUser(mPage);
			break;
		case R.id.btn_banbe:
			showDialogChuahotro();
			break;
		case R.id.btn_diemthuong:
			showDialogChuahotro();
			break;
		case R.id.btn_huyhieu:
			showDialogChuahotro();
			break;
		case R.id.btn_thongbao:
			showDialogChuahotro();
			break;
		}
	}
	
	// show dialog chua ho tro tinh nang
	public void showDialogChuahotro() {
		dH = new Dialog(getActivity(), R.style.DialogSlideAnimLeft);
		dH.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dH.setContentView(R.layout.dialog_chua_hotro);

		// khai bao cac thanh phan
		TextView txtArlert = (TextView) dH.findViewById(R.id.str_canhbao_thoat);
		Button btnDong = (Button) dH.findViewById(R.id.btn_dong);
		
		btnDong.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dH.dismiss();
			}
		});
		
		

		dH.setCanceledOnTouchOutside(true);
		dH.show();
		dH.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		dH.getWindow().setGravity(Gravity.CENTER);
	}

	// xu li phan cover slide
		private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {  
			   
	        public MyFragmentPagerAdapter(FragmentManager fm) {  
	             super(fm);  
	        }

			@Override
			public android.support.v4.app.Fragment getItem(int index) {
				android.support.v4.app.Fragment frg = null;
				switch (index) {
				case 0:
					frg = new CoverCanhan1();
					break;

				case 1:
					frg = new CoverCanhan2();
					break;
				}
				return frg;
			}

			@Override
			public int getCount() {
				return 2;
			}  
	        
		}  
		
		
		// HAM GOI DEN BO SUU TAP
		public void gotoBST() {
			Intent t = new Intent(getActivity(), ListTenBoSuuTapActivity.class);
			startActivity(t);
		}
		
		// get Data 
		public void getInfoUser () {
			HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

				@Override
				public void onFailure(Throwable error) {
					super.onFailure(error);
				}

				@Override
				public void onSuccess(JSONObject re) {
					try {
						int status = re.getInt("status");
						if (status == 200) {
							JSONObject data = re.getJSONObject("data");
							
							Log.i("DATA", "Thong tin USER: "+data.toString());
							
							String name = data.getString("name");
							String email = data.getString("email");
							String birth = data.getString("dob");
							String gender = data.getString("gender");
							String levelName = data.getString("level_name");
							String about = data.getString("about");
							int cityID = data.getInt("city_id");
							String userName = data.getString("username");
							String avatar = data.getString("avatar");
							
							int totaldadang = data.getInt("total_created");
							int totaldathich = data.getInt("total_favourite");
							Log.i("DATA", "AVATAR :"+avatar);
							
							
							preferenceHelper.setUserInfoName(name);
							preferenceHelper.setUserEmail(email);
							preferenceHelper.setUserBirth(birth);
							preferenceHelper.setUserGender(gender);
							preferenceHelper.setUserLevelName(levelName);
							preferenceHelper.setUserAbout(about);
							preferenceHelper.setUserCity(cityID);
							preferenceHelper.setUserURLAvatar(avatar);
							preferenceHelper.setUserName(userName);
							
							txtDadang.setText("Đã đăng"+"("+totaldadang+")");
							txtYeuthich.setText("Yêu thích"+"("+totaldathich+")");
							
							adapter.notifyDataSetChanged();
						} else {
							
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
				
			});
			httpClientHelper.getInfoUser(preferenceHelper.getID());
		}
		
		
		public void getActivityUser(final int page) {
			HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

				@Override
				public void onFailure(Throwable error) {
					super.onFailure(error);
					prbLoadActivity.setVisibility(View.GONE);
					Log.i("DATA", "Nhay vao thatbai");
				}

				@Override
				public void onSuccess(JSONObject re) {
					prbLoadActivity.setVisibility(View.GONE);
					Log.i("DATA", "Nhay vao sucess");
					try {
						int status = re.getInt("status");
						if (status == 200) {
							JSONArray data = re.getJSONArray("data");
							
							Log.i("DATA", "ACIVITY: "+data.toString());
							adapter.clear();
							for (int i = 0; i < data.length(); i++) {
								JSONObject jo = data.getJSONObject(i);
								JSONObject tacgia = jo.getJSONObject("author");
								
								ObjCookpad objCookpad = new ObjCookpad();
								objCookpad.setId(jo.getString("id"));
								objCookpad.setNamePersonCookpad(preferenceHelper.getUserInfoName());
								objCookpad.setDescriptionCookpad(jo.getString("desc"));	
								objCookpad.setUrlAvatar(preferenceHelper.getUserUrlAvatar());
								objCookpad.setNameCookpad(jo.getString("name"));
								// getImage
								JSONObject image = jo.getJSONObject("image");
								objCookpad.setUrlImageCookpad(image.getString("cover"));
								
								objCookpad.setThoigianNauan(jo.getString("time"));
								objCookpad.setCreatedDateCookpad(jo.getString("created"));
								objCookpad.setAction(jo.getString("action"));
								objCookpad.setViewedCookpad(jo.getInt("view_count"));
								objCookpad.setLikeCookpad(jo.getInt("like_count"));
								
								objCookpad.setIdNamePerson(tacgia.getString("id"));
								objCookpad.setNamePersonCookpad(tacgia.getString("name"));
								
								objCookpads.add(objCookpad);
								
							} 
							
							adapter.notifyDataSetChanged();
							
							
							if (objCookpads.size() > 10) {
								footerMain.setVisibility(View.VISIBLE);
							}
						} else {
							
						}
						
						
					} catch (JSONException e) {
						e.printStackTrace();
						prbLoadActivity.setVisibility(View.GONE);
					}
				}
				
			});
			httpClientHelper.getInfoActivity(preferenceHelper.getID(), page);
		}
		
		
		// logout
		void logout() {
			web.setWebViewClient(new MyWebViewClient());
			web.loadUrl(urllogout);
		}
		
		private class MyWebViewClient extends WebViewClient {
		    @Override
		    public boolean shouldOverrideUrlLoading(WebView view, final String url) {
		       view.loadUrl(url);
		        return true;
		    }

			@Override
			public void onPageStarted(WebView view, final String url, Bitmap favicon) {
				       if (url.startsWith(urlRsLogout)) {
							Thread tr = new Thread(){

								@Override
								public void run() {
									String str = "";
							        HttpResponse response;
							        HttpClient myClient = new DefaultHttpClient();
							        HttpPost myConnection = new HttpPost(url);
							         Log.i("DATA", "--------------1");
							        try {
							            response = myClient.execute(myConnection);
							            Log.i("DATA", "--------------2");
							            str = EntityUtils.toString(response.getEntity(), "UTF-8");
							            Log.i("DATA", "DATA CHUA PASER: "+str);
							        } catch (ClientProtocolException e) {
							            e.printStackTrace();
							        } catch (IOException e) {
							            e.printStackTrace();
							        }
							        

				             try{
						            JSONObject jo = new JSONObject(str);
						            
						            int status = jo.getInt("status");
						            if (status == 200) {
						            	
						            	Intent t = new Intent(getActivity(), LoginActivity.class);
						            	getActivity().finish();
						            	t.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
						            	startActivity(t);
						            	preferenceHelper.setID("");
						            	progressDialog.dismiss();
						            	
						            } else {
						            	progressDialog.dismiss();
						            	Toast.makeText(getActivity(), "Thoát thất bại.", Toast.LENGTH_SHORT).show();
									}
						            	/*preferenceHelper.setID(userID);
						            	preferenceHelper.setUserInfoName(data.getString("name"));
						            	preferenceHelper.setUserEmail(data.getString("email"));
						            	preferenceHelper.setUserURLAvatar(data.getString("avatar"));
						            	preferenceHelper.setUserBirth(data.getString("dob"));
						            	preferenceHelper.setUserGender(data.getString("gender"));
						            	preferenceHelper.setUserAbout(data.getString("about"));
						            	preferenceHelper.setUserName(data.getString("username"));
//						            	preferenceHelper.setUserCity(data.getInt("city_id"));
*/									
						            }
						            
						             
						        catch ( JSONException e) {
						            e.printStackTrace();                
						        }
								}
								
							};
							tr.start();

						}
				}
			}
		    
		
		void addFooterView() {
			View loadMoreView = ((LayoutInflater) this.getActivity()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
					R.layout.footer_loadmore, null, false);
			footerMain = (View) loadMoreView.findViewById(R.id.footer_main);
			footerMain.setVisibility(View.GONE);
			getListView().addFooterView(loadMoreView);
			btnLoadMore = (Button) loadMoreView.findViewById(R.id.btn_load_more);
			progressBarLoadmore = (ProgressBar) loadMoreView.findViewById(R.id.progressBar1);
			btnLoadMore.setOnClickListener(this);
		}
		
		 public void setListViewHeightBasedOnChildren(ListView listView) {
	         ArrayAdapter listAdapter = (ArrayAdapter) listView.getAdapter(); 
	            if (listAdapter == null) {
	                // pre-condition
	                return;
	            }

	            int totalHeight = 0;
	            for (int i = 0; i < listAdapter.getCount(); i++) {
	                View listItem = listAdapter.getView(i, null, listView);
	                listItem.measure(0, 0);
	                totalHeight += listItem.getMeasuredHeight();
	            }

	            ViewGroup.LayoutParams params = listView.getLayoutParams();
	            params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
	            listView.setLayoutParams(params);
	            listView.requestLayout();
	        }
		
}
